package org.sharkness.web.authority;

import java.util.List;

import org.sharkness.business.entity.User;
import org.sharkness.business.factory.PropertiesFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

@SuppressWarnings("unchecked")
public class CustomUserDetailsService  extends HibernateDaoSupport implements UserDetailsService {

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
		
		String hql = PropertiesFactory.getSharknessProperties().getProperty("sharkness.database.username.hql");
		
		List<User<?>> results = getHibernateTemplate().find(hql, new Object[] {username});
	
		if(results.size() < 1) throw new UsernameNotFoundException(username + "not found");
		
		User<?> user = results.get(0);
		
		if (!user.isAtivo()) {
			
			user.setEnabled(false);
			
		} else if (user.getTries() >= 3) {
			
			user.setAccountNonLocked(false);
			
		}
		
		return (UserDetails) user;
		
	}
	
}